/*!
\copyright  Copyright (c) 2024 Qualcomm Technologies International, Ltd.
            All Rights Reserved.
            Qualcomm Technologies International, Ltd. Confidential and Proprietary.
\file
\brief      Support for accelerometer/gyroscope where driver is supplied by sensor subsystem
*/

#ifdef HAVE_SENSORSS

#include <panic.h>
#include <stdlib.h>
#include <logging.h>
#include <pl_timers/pl_timers.h>
#include "adk_log.h"
#include "acceleration.h"
#include "imu_sensorss.h"
#include "acceleration_config.h"
#include "app_sensor.h"


/* Make the type used for message IDs available in debug tools */
LOGGING_PRESERVE_MESSAGE_ENUM(accelerometer_messages)
accelTaskData app_accelerometer;

static void imuSensorSs_MessageHandler(Task task, MessageId id, Message msg)
{
    accelTaskData *imu = (accelTaskData *) task;
    int16_t gravity_direction = (((const SENSOR_SS_IMU_EVENT_T *)msg)->accel_data).z;

    DEBUG_LOG("IMUSs_MessageHandler MSG:Accel_module_internal_messages:%d", id);
    if (imu->clients != NULL)
    {
        switch(id)
        {
            case SENSOR_SS_IMU_EVENT:
                    if (gravity_direction > 0)
                    {
                        DEBUG_LOG_VERBOSE(" IMU  upside down");
                        TaskList_MessageSendId(imu->clients, ACCELEROMETER_MESSAGE_UPSIDE_DOWN);

                    }
                    else
                    {
                        DEBUG_LOG_VERBOSE(" IMU right side up ");
                        TaskList_MessageSendId(imu->clients, ACCELEROMETER_MESSAGE_RIGHT_SIDE_UP);
                    }
                    break;

            default:
            /* Unknown ID */
                DEBUG_LOG_ALWAYS(" ID not recognised ");
                break;
        }
    }
}

bool appAccelerometerClientRegister(Task task)
{
    accelTaskData *imu = AccelerometerGetTaskData();

    if (NULL == imu->clients)
    {
        imu->config = NULL;
        imu->clients = TaskList_Create();
        imu->task.handler = imuSensorSs_MessageHandler;
    }

    MessageSend(task, ACCELEROMETER_MESSAGE_NOT_IN_MOTION, NULL);

    DEBUG_LOG_VERBOSE("Accelerometer Client registered");
    return TaskList_AddTask(imu->clients, task);
}

void appAccelerometerClientUnregister(Task task)
{
    accelTaskData *imu = AccelerometerGetTaskData();
    TaskList_RemoveTask(imu->clients, task);
    if (0 == TaskList_Size(imu->clients))
    {
        TaskList_Destroy(imu->clients);
        imu->clients = NULL;
    }
}

Task ImuSensorGetTask(void)
{
    return &app_accelerometer.task;
}

bool appAccelerometerGetDormantConfigureKeyValue(dormant_config_key *key, uint32* value)
{
    UNUSED(key);
    UNUSED(value);

    return FALSE;
}

#endif /* HAVE_SENSORSS */